/*****************************************************************
**                                                             	**
**  Copyright (C) 2004 Amlogic,Inc.                            	**
**  All rights reserved                                        	**
**        Filename : aw_bluetooth.c /Project:AVOS  				** 
**        Revision : 1.0                                       	**
**                                                             	**
*****************************************************************/
#include "user.h"
#ifdef ENABLE_BLUETOOTH
#include "includes.h"
#include "aw_windows.h"
#include "user.h"
#include "filenav.h"
#include "aw_gui_app.h"
#include "aw_sys_app.h"
#include "aw_init_display.h"
#include "aw_PIC_app.h"
#include "logo_dat.h"
#include "LogoEvent.h"
#include "NetmenuSetupEvent.h"
#include "aw_bluetooth.h"
#include "btdev.h"
#include <Drivers/bluetooth/bt_customer.h>
#include "filesystem/extend/fileio.h"

static unsigned short bt_ftp_status = 0;
static unsigned short bt_opp_status = 0;
extern char CurrentDevPath[12]; //the current Device path eg:"/mnt/c"
extern char CurDriver[10];
char nand_pathname[16];
char nand_name[16];
char bt_local_name[16] = "Amlogic";
int gBluetoothFlag = BLUETOOTH_DISABLE;
char *file_current_addr = "" ;
extern char gCurOnlyFileName[256] ;
//BT_Device_t *bt_dev = NULL;

int IfBtDeviceInsert(void) 
{
	return gBluetoothFlag;
}

int BtSendDevCmd(unsigned cmd, void *arg)
{
	int fd,rc;
	fd = open(BT_DRIVER_NAME,O_RDWR);
	if(fd<0)
		return -1;
	rc = ioctl(fd,cmd,arg);
	if(rc<0)
	{
		close(fd);
		return -1;
	}
	
	close(fd);
	
	return rc;
}

char* GetBtLinkKeyAddr(void)
{
	char** key;
	BtSendDevCmd(BT_IOCMD_GET_LINK_KEY,&key);
	return (*key + 1);
}

void InitBtLinkKey(void)
{
	char** key;

	BtSendDevCmd(BT_IOCMD_GET_LINK_KEY,&key);
	if(*key)
		AVMem_free(*key) ;
	*key = AVMem_malloc(2+MAX_LINK_KEY_NUM*sizeof(bt_link_key_t));
	memset(*key,0,2+MAX_LINK_KEY_NUM*sizeof(bt_link_key_t));
	**key = MAX_LINK_KEY_NUM;	//max link key number
	*(*key + 1) = 0;			//current link key number
	return;
}

#ifdef ENABLE_BLUETOOTH_OPP
int opp_copy_flag = 0;
static char btopp_pathname[16];
static char btopp_file_name[64];
static char btopp_size_str[16];
static char btopp_remote_dev_name_str[248];
static int btopp_file_size = 0;

extern void PicPlayer(char *filename);

char *Jpeg_Extname[4] = {   
    {".jpeg"}, 
    {".jpe"},  
    {".jpg"},
    {".bmp"} 
};

char *Gif_Extname[1] = {    
    {".gif"}  
};

INT8U CheckJPEG_Picture(char *extname)
{
    INT8U i;
    for(i = 0;i<4;i++){
        if ((extname) && (strcasecmp(extname, Jpeg_Extname[i]) == 0)) {
            return 1;
        }
    }
    return 0;
}

INT8U CheckGIF_Picture(char *extname)
{
    if ((extname) && (strcasecmp(extname, Gif_Extname[0]) == 0)) {
        return 1;
    }
    return 0;
}

//0:Transfer file if not exist or cancel transfer, 
//1:Play picture file directly.
//2:same with 0 except that do not load logo and show menu.
void BTShowFileTransferWin(unsigned char mode)
{
	char name, *file_name, *opp_file_name, *text;
	int len=0;

	//Get file info only once at the beginning of file processing, then auto update file info index.
	BtSendDevCmd(BT_IOCMD_OPP_GET_FILE_NAME,&opp_file_name);
	BtSendDevCmd(BT_IOCMD_OPP_GET_TOTAL_FILE_SIZE,&btopp_file_size);
	text = strrchr(opp_file_name, '.') ;
	name = *opp_file_name;
	len = strlen(opp_file_name);

	if(name)
	{
		strcpy(btopp_file_name,opp_file_name);

		FileNavCD(CurDriver) ;
            
    #if 0
		if(AWGetTopWindow(gpFocusWin) != AWFindWinCtrlByName("BluetoothMain"))
		{
			BTInitData(2);
			GUIShowWindow("BluetoothMain");
			if(!strcmp(nand_name, "nanda1"))
			{
				ReloadLogo(Logo_keyboard, sizeof(Logo_keyboard), 1);
			}
		}
    #endif
	  if(mode == 0)
		{
            INT8U my_app_id ;
            AWGetAppID(MEDIA_PIC, &my_app_id) ; 
           if (AWGetAppStatus(my_app_id) != APP_RUNNING)
            {
                //extern void send_pic_player_quit(void);
                //send_pic_player_quit();
                //AWPICQuitProcess(0xff);
//			    GUIShowWindow("WinLogo");
                          
    			//if(!strcmp(nand_name, "nanda1"))
    			{
	        		if(CheckMediaPlaybackApp()){
	        			CloseMediaPlaybackApp(0xff);
				
	        		}
    			}
            }
		}
		file_name = AVMem_malloc(len + strlen(btopp_pathname) + 1);
		if(file_name == NULL)
			goto BT_SHOW_FILE_END;
		strcpy(file_name, btopp_pathname);
		strcat(file_name, opp_file_name);
		if((mode == 1) || (strcmp(nand_name, "nanda1")!= 0))
		{
			//GUIHideWindow("BluetoothMain");
			if(CheckJPEG_Picture(text) || CheckGIF_Picture(text))
			{
				PicPlayer(file_name);
				AVMem_free(file_name);
				return;
			}
			else
			{
				BtSendDevCmd(BT_IOCMD_OPP_ABORT,NULL);
				AVMem_free(file_name);
			}
		}
		else
		{
			AWSysCopyDelFile(file_name, SYS_COPY_FILE) ;
			AVMem_free(file_name);
			return;
		}
	}
	else
	{
		BtSendDevCmd(BT_IOCMD_OPP_ABORT,NULL);
	}
BT_SHOW_FILE_END:
	AWShowFileList(1);
	return;
}

//0:Check if it is picture file after transfered, if yes play it. 1:If cancel file transfer, del the file.
void BTHideFileTransferWin(unsigned char mode)
{
	char name, *file_name, *text;
	int len;

	text = strrchr(btopp_file_name, '.') ;
	name = *btopp_file_name;
	len = strlen(btopp_file_name);

	//GUIHideWindow("BluetoothMain");
//	if(!name)
//		goto BT_HIDE_FILE_END;
	if(mode == 0)
	{
		/*if((CheckJPEG_Picture(text) == 0) && (CheckGIF_Picture(text) == 0))
			goto BT_HIDE_FILE_END;*/
	}
	file_name = AVMem_malloc(len + strlen(file_current_addr) + 1);
	
//	if(file_name == NULL)
//		goto BT_HIDE_FILE_END;
		
	strcpy(file_name, file_current_addr);
	strcat(file_name, btopp_file_name);
	if(mode == 0)
	{ 
	INT32U item_type ;
	item_type = GetMediaType(file_name) ;
	if(!CheckMediaPlaybackApp())
		{
	  if(item_type & AW_AUDIO_LIST)
	  	AudioPlayer(file_name);
	  else if(item_type & MEDIA_PIC)	
        PicPlayer(file_name);
		}
		AVMem_free(file_name);
		
		return;
	}
	else if (mode == 1)
	{
		AWSysCopyDelFile(file_name, SYS_DEL_FILE) ;
		AVMem_free(file_name);
	}
	else
	{
		AVMem_free(file_name);
	}
//BT_HIDE_FILE_END:
//	cur_func_index=6;
//	change_window_no_file();
}

unsigned char OppIfFileTransferDone(void)
{
	int c_size=0;

	BtSendDevCmd(BT_IOCMD_OPP_GET_CUR_FILE_SIZE,&c_size);
	
	return (c_size < btopp_file_size)?0:1;
}

static void BtTransferInt2Str(int num)
{
	char tmp_str[8];

	if(!num)
	{
		strcat(btopp_size_str,"0");
	}
	else
	{
		for(int index=0,mod=10000,i=4;i>=0;i--)
		{
			if((num/mod) || index)
				tmp_str[index++] = '0' + num/mod;
			num %= mod;
			mod /= 10;
		}
		tmp_str[index] = 0;
		strcat(btopp_size_str,tmp_str);
	}
}
static void BTOppGetFileSize(void)
{
	int size = 0;
	
	memset(btopp_size_str,0,sizeof(btopp_size_str));
	BtSendDevCmd(BT_IOCMD_OPP_GET_CUR_FILE_SIZE,&size);
	if(size >= 0)
		BtTransferInt2Str(size/1024);
	strcat(btopp_size_str,"KB/");
	
	if(btopp_file_size >= 0)
		BtTransferInt2Str(btopp_file_size/1024);
	strcat(btopp_size_str,"KB");
}

void BTMainGuiOppRefreshFilePara(PHWND hwnd)
{
	if(hwnd->draw_info)
	{
		BTOppGetFileSize();
		hwnd->draw_info[1].draw_data = (INT32U)btopp_file_name;
		hwnd->draw_info[2].draw_data = (INT32U)btopp_size_str;
		AWPostMessage(hwnd, WM_PAINT_DRAW_INFO_CENTER, 1) ;
		AWPostMessage(hwnd, WM_PAINT_DRAW_INFO_CENTER, 2) ;
	}
	return ;
}
#endif


#ifdef ENABLE_BLUETOOTH_FTP
char btftp_pathname[16];

int BtSendFtpCmd(char *name,unsigned cmd, void *arg)
{
	int fd,rc;
	
	if(!(*name))
		return -1;
		
	fd = open(name,O_RDWR);
	
	if(fd<0)
		return -1;
		
	rc = ioctl(fd,cmd,arg);
	
	if(rc<0)
	{
		close(fd);
		
		return -1;
	}
	
	close(fd);
	
	return rc;
}

void ResetCurPathNode(void)
{
    INT8U my_app_id ;
    INT16U pCmds = CM_RESET_CURPATHNODE;
    INT32U pCmdsParam = 0;
    INT8U pCmdTimeOut = 0;

    AWGetAppID(MEDIA_SYSTEM, &my_app_id) ; 
    AWAddCmdSet(1, &pCmds, &pCmdsParam, &pCmdTimeOut, my_app_id, NULL) ;
}
#endif


void SetBtStatus(unsigned char type,unsigned short status)
{
	if(type == BLUETOOTH_OPP)
		bt_opp_status = status;
	else if(type == BLUETOOTH_FTP)
		bt_ftp_status = status;
#ifdef ENABLE_BLUETOOTH_AUDIO
	else if(type == BLUETOOTH_AUDIO)
		bt_audio_status = status;
#endif
}
unsigned short GetBtStatus(unsigned char type)
{
	if(type == BLUETOOTH_OPP)
		return bt_opp_status;
	else if(type == BLUETOOTH_FTP)
		return bt_ftp_status;
#ifdef ENABLE_BLUETOOTH_AUDIO
	else if(type == BLUETOOTH_AUDIO)
		return bt_audio_status;
#endif
	else
		return 0;
}

void AWBTNotificationProcess(AWMSG *pMsg)
{
	switch(pMsg->msg_id)
	{
		case NM_END_OF_PLAY:
#ifdef ENABLE_BLUETOOTH_OPP
			switch(pMsg->msg_value)
			{
				case -SYS_DISK_FULL:
					if(opp_copy_flag&0x7f)
					{
						opp_copy_flag = 0;
						BTShowFileTransferWin(1);
					}
					break;
				case -SYS_COPY_CANCELLED:
					break;
				default:
					if(opp_copy_flag&0x7f)
						opp_copy_flag--;
					if(opp_copy_flag&0x7f)
					{
						BTShowFileTransferWin(2);
					}
					else if(opp_copy_flag&0x80)
					{
						opp_copy_flag = 0;
						BTHideFileTransferWin(0);
						BtSendDevCmd(BT_IOCMD_OPP_RELEASE_FILE_INFO,NULL);
					}
					break;
			}
#endif
			break;
		default:
			break;
	}
	return;
}

void AWBTBroadCastProcess(AWMSG *pMsg)
{
	PHWND hwnd;
	switch(pMsg->msg_id)
	{
		case BM_DEVICE_POST_MOUNT:
			char* FileName = ((DEV_MOUNT_INFO *)(pMsg->msg_value))->mount_device_name;
			
			if(strcmp((const char *)FileName, "nanda1") == 0)
			{
				strcpy(nand_name,"nanda1");
				FileName = ((DEV_MOUNT_INFO *)(pMsg->msg_value))->mount_point_name;
				strcpy(nand_pathname,(const char *)FileName);
				strcat(nand_pathname,"/");
				break;
			}
#ifdef ENABLE_BLUETOOTH_OPP
			if(strcmp((const char *)FileName, "bt_opp") == 0)
			{
				FileName = ((DEV_MOUNT_INFO *)(pMsg->msg_value))->mount_point_name;
				strcpy(btopp_pathname,(const char *)FileName);
				strcat(btopp_pathname,"/");
				if(gBluetoothFlag == BLUETOOTH_DISABLE)
					BtSendDevCmd(BT_IOCMD_GET_STATUS,&gBluetoothFlag);
				if(gBluetoothFlag == BLUETOOTH_ENABLE)
					BtSendDevCmd(BT_IOCMD_SET_LOC_NAME,bt_local_name);
				break;
			}
#endif
#ifdef ENABLE_BLUETOOTH_FTP
			if(strcmp((const char *)FileName, "bt_ftp") == 0)
			{
				FileName = ((DEV_MOUNT_INFO *)(pMsg->msg_value))->mount_point_name;
				strcpy(btftp_pathname,(const char *)FileName);
				strcat(btftp_pathname,"/");
				if(gBluetoothFlag == BLUETOOTH_DISABLE)
					BtSendDevCmd(BT_IOCMD_GET_STATUS,&gBluetoothFlag);
				if(gBluetoothFlag == BLUETOOTH_ENABLE)
					BtSendDevCmd(BT_IOCMD_SET_LOC_NAME,bt_local_name);
				break;
			}
#endif
			break;
        case BM_DEVICE_POST_UNMOUNT:
#ifdef ENABLE_BLUETOOTH_FTP
			if(((AWGetTopWindow(gpFocusWin) == AWFindWinCtrlByName("BluetoothMain"))|| (strncmp(CurrentDevPath,btftp_pathname,6) == 0)) && (strncmp(((DEV_MOUNT_INFO *)(pMsg->msg_value))->mount_point_name, btftp_pathname,6)==0))
#endif
#ifdef ENABLE_BLUETOOTH_OPP
			if(AWGetTopWindow(gpFocusWin) == AWFindWinCtrlByName("BluetoothMain"))
#endif

				{
					GUIHideWindow("BluetoothMain");
					strcpy(CurrentDevPath, nand_pathname);
					FileNavCD(CurrentDevPath);
					AWShowFileList(1);
				}
			break;
        
		case BM_TIMEOUT:
			int event = -1;
			BtSendDevCmd(BT_IOCMD_GET_EVENT,&event);
			if(event == -1)
				break;
			switch(event)
			{
				case BT_EVENT_INSERT:
#if ((defined ENABLE_BLUETOOTH_AUDIO) && !(defined ENABLE_BLUETOOTH_OPP) && !(defined ENABLE_BLUETOOTH_FTP))
					BtSendDevCmd(BT_IOCMD_ENABLE,&gBluetoothFlag);
#endif
					if(gBluetoothFlag == BLUETOOTH_DISABLE)
						BtSendDevCmd(BT_IOCMD_GET_STATUS,&gBluetoothFlag);
					if(gBluetoothFlag == BLUETOOTH_ENABLE)
						BtSendDevCmd(BT_IOCMD_SET_LOC_NAME,bt_local_name);
					break;
				case BT_EVENT_REMOVE:
					if(gBluetoothFlag == BLUETOOTH_ENABLE)
					{
#ifdef ENABLE_BLUETOOTH_OPP
						BtSendDevCmd(BT_IOCMD_OPP_RELEASE_FILE_INFO,NULL);
#endif
						BtSendDevCmd(BT_IOCMD_DISABLE,NULL);
						gBluetoothFlag = BLUETOOTH_DISABLE;
					}
					break;
				case BT_EVENT_CONNECT:
#ifdef ENABLE_BLUETOOTH_OPP
					if(opp_copy_flag&0x7f)
					{
						opp_copy_flag++;
						break;
					}
					opp_copy_flag++;
//					SetBtLinkKey();
					BtSendDevCmd(BT_IOCMD_GET_REMOTE_NAME,&btopp_remote_dev_name_str);
					if(GetBtStatus(BLUETOOTH_OPP) != BM_DEVICE_BT_CONNECT)
					{
						SetBtStatus(BLUETOOTH_OPP,0);
						BTShowFileTransferWin(0);
					}
#endif
					break;
				case BT_EVENT_DISCONNECT:
#ifdef ENABLE_BLUETOOTH_OPP
					if(!OppIfFileTransferDone() && !strcmp(nand_name, "nanda1"))
					{
						BtSendDevCmd(BT_IOCMD_OPP_ABORT,NULL);
						opp_copy_flag = 0;
						BTHideFileTransferWin(1);
						break;
					}
					if(opp_copy_flag&0x7f)
					{
						opp_copy_flag |= 0x80;
					}
					else
					{
						opp_copy_flag = 0;
						BTHideFileTransferWin(0);
						BtSendDevCmd(BT_IOCMD_OPP_RELEASE_FILE_INFO,NULL);
					}
#endif
#ifdef ENABLE_BLUETOOTH_AUDIO
					if(GetBtStatus(BLUETOOTH_AUDIO) == BM_DEVICE_BT_CONNECT)
						SetBtStatus(BLUETOOTH_AUDIO,0);
#endif
					break;
				case BT_EVENT_DEV_DOWN: //In case that the remote bt device disconnect under FTP mode.
#ifdef ENABLE_BLUETOOTH_FTP
					if((AWGetTopWindow(gpFocusWin) == AWFindWinCtrlByName("BluetoothMain"))
					|| (strcmp(CurrentDevPath,btftp_pathname) == 0))
					{
						GUIHideWindow("WinLogo");
						strcpy(CurrentDevPath, nand_pathname);;
						FileNavCD(CurrentDevPath);
						AWShowFileList(1);
					}
					if(gBluetoothFlag)
					{
						BtSendDevCmd(BT_IOCMD_FTP_CLOSE,NULL);
						BtSendDevCmd(BT_IOCMD_FTP_CANCEL,NULL);
						BtSendFtpCmd(btftp_pathname,FILE_IOCTL_RELEASE_ALL,NULL); //release file system resource after bt ftp close.
					}
#endif
					break;
				case BT_EVENT_PIN_CODE_REQUEST:
#ifdef ENABLE_BLUETOOTH_AUDIO
					if(GetBtStatus(BLUETOOTH_AUDIO) == BM_DEVICE_BT_CONNECT)
						BtSendDevCmd(BT_IOCMD_SET_TMP_PIN_CODE,&BtAudioPinCode);
					else
#endif
						BtSendDevCmd(BT_IOCMD_SET_TMP_PIN_CODE,NULL);
					break;
				default:
					break;
			}
			break;
	}

	if(gBluetoothFlag == BLUETOOTH_ENABLE)
	{
		#if 0  // don't show bluetooth icon
		hwnd = AWFindWinCtrlByName("BLUETOOTHGUIControl1");
		if (hwnd)
		{
			if (hwnd->draw_info[0].draw_data != (INT32U)ICON_BLUETOOTH) 
			{         
				hwnd->draw_info[0].draw_data = (INT32U)ICON_BLUETOOTH;
				if (AWIsVisibleWinControl(AWFindWinCtrlByName("MediatypeSelect")))   
					AWShowWinControl(hwnd,0);
			}
		}
		#endif //0
		hwnd = AWFindWinCtrlByName("WarningControl20");
		if (hwnd)
		{
			if (AWIsVisibleWinControl(hwnd))
				AWHideWinControl(hwnd) ;
		}
	}
	#if 0  // don't hide bluetooth icon
	else
	{
		hwnd = AWFindWinCtrlByName("BLUETOOTHGUIControl1");
		if (hwnd)
		{
			if (hwnd->draw_info[0].draw_data != (INT32U)0) 
			{    
				hwnd->draw_info[0].draw_data = (INT32U)0;
				if (AWIsVisibleWinControl(AWFindWinCtrlByName("MediatypeSelect")))   
					AWHideWinControl(hwnd) ;
			}
		}
	}
	#endif //0

	return;
}
#endif //ENABLE_BLUETOOTH